import jwt from 'jsonwebtoken'
import type { SafeUserData } from '../models/User'

// JWT配置
const JWT_SECRET = process.env.JWT_SECRET || 'blog_nuxt-qW5pC6qF3tX4gI0j'
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d'

export interface JwtPayload {
  userId: number
  username: string
  role: string
}

// 生成JWT token
export function generateToken(user: SafeUserData): string {
  return jwt.sign(
    {
      userId: user.id!,
      username: user.username,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN as jwt.SignOptions['expiresIn'] }
  )
}

// 验证JWT token
export function verifyToken(token: string): JwtPayload | null {
  try {
    return jwt.verify(token, JWT_SECRET) as JwtPayload
  } catch (error) {
    return null
  }
}

// 从请求头中提取token
export function extractTokenFromHeader(authHeader?: string): string | null {
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null
  }
  return authHeader.substring(7)
}

// 生成随机字符串
export function generateRandomString(length: number = 32): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 生成slug
export function generateSlug(title: string): string {
  return title
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '') // 移除特殊字符
    .replace(/[\s_-]+/g, '-') // 替换空格和下划线为连字符
    .replace(/^-+|-+$/g, '') // 移除开头和结尾的连字符
}

// 计算阅读时间（基于字数）
export function calculateReadingTime(content: string): number {
  const wordsPerMinute = 200 // 平均每分钟阅读字数
  const wordCount = content.length / 2 // 中文字符数估算
  return Math.ceil(wordCount / wordsPerMinute)
}

// 生成文章摘要
export function generateExcerpt(content: string, maxLength: number = 200): string {
  // 移除HTML标签
  const textContent = content.replace(/<[^>]*>/g, '')
  
  if (textContent.length <= maxLength) {
    return textContent
  }
  
  return textContent.substring(0, maxLength).trim() + '...'
}